<?php

namespace app\common\logic;

use app\common\lib\crypts\OpenSSLAES;
use PHPExcel_IOFactory;
use think\Cache;
use think\Db;
use think\Exception;
use think\Loader;

/**
 * 业务逻辑 - 基类
 * Class Logic
 */
abstract class Logic
{
    /**
     * 是否为微信端
     * @return bool
     */
    static public function is_wechat()
    {
        return strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ? true : false;
    }

    /**
     * 获取当前页面完整URL地址
     */
    static public function get_current_url()
    {
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
        $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
        $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
        log_print($sys_protocal,$relate_url);
//        return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;

        return 'https://ke.bigchun.com' . $relate_url;
    }

    /**
     * 校验手机格式
     * @param $phone
     * @return array|\think\response\Json
     */
    static public function check_phone($phone)
    {
        if (strlen($phone) != 11) return ['code' => 0, 'msg' => '长度不对'];

        $match = "/1(3|4|5|7|8|9)\d{9}/";

        if (!preg_match($match, $phone)) {
            trace($phone, 'error');
            return ['code' => 0, 'msg' => '手机号格式不正确'];
        }

        return ['code' => 1, '手机格式正确'];
    }

    /**
     * 校验邮箱
     * @param $email
     * @return array
     */
    static function check_email($email)
    {
        $checkmail = "/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/";

        if (!preg_match($checkmail, $email)) {
            trace($email, 'error');
            return ['code' => 0, 'msg' => '邮箱格式不正确'];
        }

        return ['code' => 1, '邮箱格式正确'];
    }

    /**
     * 读取excel
     * @param $file_name
     * @param int $index
     * @return array
     */
    static public function read_excel($file_name, $index = 0)
    {
        try {
            Loader::import('phpexcel.PHPExcel');
            Loader::import('phpexcel.PHPExcel.IOFactory.PHPExcel_IOFactory');
            Loader::import('phpexcel.PHPExcel.Reader.Excel5.php');

            $PHPReader = PHPExcel_IOFactory::createReader('Excel5');

            // 载入文件
            $file_name = iconv('utf-8', 'gb2312', $file_name);

            $file_name = ROOT_PATH . 'public' . DS . $file_name;
            $PHPExcel = $PHPReader->load($file_name);
            // 获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
            $currentSheet = $PHPExcel->getSheet($index);

            //获取总行数
            $row_num = $currentSheet->getHighestRow();
            //获取总列数
            $col_num = $currentSheet->getHighestColumn();

            $title = [];
            $content = [];

            for ($col = 'A'; $col <= $col_num; $col++) {
                $cell = $currentSheet->getCell($col . '1')->getValue();
                array_push($title, $cell);
            }

            for ($row = 2; $row <= $row_num; $row++) {
                $row_cell = [];
                for ($col = 'A'; $col <= $col_num; $col++) {
                    $cell = $currentSheet->getCell($col . $row)->getValue();
                    array_push($row_cell, $cell);
                }
                array_push($content, $row_cell);
            }

            return ['title' => $title, 'content' => $content];
        } catch (Exception $e) {
            log_print($e->getMessage());
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 导出excel
     * @param $title
     * @param $content
     * @param $filename
     */
    static function output_excel($title, $content, $filename)
    {
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:filename=" . $filename . ".xls");

        $strexport = "";
        foreach ($title as $row) {
            $strexport .= $row . "\t";
        }
        $strexport .= "\r";

        foreach ($content as $v) {
            foreach ($v as $row) {
                $strexport .= $row . "\t";
            }
            $strexport .= "\r";
        }
        $strexport = iconv('UTF-8', "GB2312//IGNORE", $strexport);
        exit($strexport);
    }

    /**
     * AES解密
     * @param $card
     * @return string
     */
    public static function aesDecrypt($card)
    {
        return OpenSSLAES::decryptWithOpenssl($card);
    }

    /**
     * AES加密
     * @param $card
     * @return string
     */
    public static function aesEncrypt($card)
    {
        $result = OpenSSLAES::encryptWithOpenssl($card);
        return str_replace('=', '', $result);
    }

    /**
     * 转化时间戳
     * @param $time
     * @return int
     */
    public static function convert_timestamp($time)
    {
        $arr = explode(':', $time);

        if (count($arr) == 2) return $arr[0] * 3600 + $arr[1] * 60;

        if (count($arr) == 3) return $arr[0] * 3600 + $arr[1] * 60 + $arr[2];

        return 0;
    }

    public static function logout()
    {
        session('user_login_info', null);
        session('url_refer', null);
        session_destroy();
    }

    public static function is_debug()
    {
        $secret = config('secret');
        return (config('app_debug') == true) || (!empty($secret) && session('secret') == config('secret'));
    }

}